package com.smart.wap.service;

import cn.hutool.core.lang.Assert;
import com.smart.manager.finance.entities.enums.PayState;
import com.smart.manager.finance.entities.models.FinanceOrderCoin;
import com.smart.manager.finance.repository.OrderCoinRepository;
import com.smart.manager.finance.repository.OrderPopRepository;
import com.smart.manager.member.entities.enums.CoinAccountEvent;
import com.smart.manager.member.entities.views.MemberView;
import com.smart.manager.member.repository.MemberAccountRepository;
import com.smart.manager.pop.repository.DisBillRepository;
import com.smart.manager.pop.repository.DisLevelRepository;
import com.smart.service.remind.RemindService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author Administrator
 */
@Service
@Log4j2 @RequiredArgsConstructor
public class PaySuccessHandler {

    private final RemindService remindService ;
    private final OrderCoinRepository orderCoinRepository ;
    private final OrderPopRepository orderPopRepository ;
    private final MemberAccountRepository memberAccountRepository ;
    private final DisLevelRepository disLevelRepository ;
    private final DisBillRepository disBillRepository ;
    /**
     * 金币订单充值成功回调
     * @param outTradeNo
     * @param transactionId
     * @param payAmount
     */
    @Transactional(rollbackFor = Exception.class)
    public void onCoinSuccess(String outTradeNo, String transactionId, BigDecimal payAmount) {
        FinanceOrderCoin orderCoin = orderCoinRepository.getOneByOrderId(outTradeNo);
        Assert.equals(payAmount,orderCoin.getFee() ,"订单金额和交易金额不一致");
        Assert.equals(orderCoin.getPayState() , PayState.NOT_PAID , "当前订单不已处理过的状态了");
        MemberView member = orderCoin.getMember();
        String remark = String.format("%s充值%s元, 交易流水号:%s", orderCoin.getPayPlatform().getLabel(), payAmount, transactionId);
        //实际应该获得的金币
        Integer coinTotal = orderCoin.getCoinTotal();
        memberAccountRepository.saveEvent(member.getId() , CoinAccountEvent.RECHARGE ,coinTotal,remark);
        orderCoin.setPayState(PayState.PAID).setFinishTime(LocalDateTime.now()).setTransactionId(transactionId).update();
        //消息提醒
        remindService.sendBuyCoinMsg(member.getId() ,orderCoin );
    }



}
